package com.tedu.weibo.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/*
* 用于为所有Controller处理请求方法记录日志
* 需求:
* 在调用Controller方法前记录日志,记录对应方法调用了        @before          log.info
* 在调用Controller方法之后记录日志,记录对应方法调用完毕    @afterReturning  log.info
* 如果方法出现异常也需要记录                              @afterThrowing   log.error
*
* 1:在当前类上添加三个注解
* 2:定义三个切入方法,每个方法中记录日志
*   在切入点注解描述切入点信息(每个Controller的每个方法上都要进行)
* */
@Aspect
@Component
@Slf4j
public class LogAspect {
    @Before("execution(public com.tedu.weibo.result.JsonResult com.tedu.weibo.controller.*.*(..))")
    public void before(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        log.info(className+"."+methodName+"()方法开始调用了...");
    }

    @AfterReturning("execution(public com.tedu.weibo.result.JsonResult com.tedu.weibo.controller.*.*(..))")
    public void afterReturning(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        log.info(className+"."+methodName+"()方法调用完毕");
    }

    @AfterThrowing(
            value = "execution(public com.tedu.weibo.result.JsonResult com.tedu.weibo.controller.UserController.*(..))",
            throwing = "e"
    )
    public void afterThrowing(JoinPoint joinPoint,Exception e){
        /*String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        System.out.println(className+"."+methodName+"()方法出现异常了,异常信息为"+e.getMessage());*/
        log.error(e.getMessage(),e);
    }

    /*@Around("execution(public * com.tedu.weibo.controller.*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        try {
            //@Before
            System.out.println(className+"."+methodName+"()方法开始调用了..");
            //使用切入点对象调用时机方法
            Object returnValue = joinPoint.proceed();//比如calculator.add(1,2);
            //@AfterReturning
            System.out.println(className+"."+methodName+"()方法调用完毕,返回值为:"+returnValue);
            return returnValue;
        } catch (Throwable e) {
            //@AfterThrowing
            System.out.println(className+"."+methodName+"()方法出现异常了,异常信息为:"+e.getMessage());
            throw new RuntimeException(e);
        }finally {
            //@After()
            System.out.println(className+"."+methodName+"()方法最终执行完毕");
        }
    }*/
}
